<?php

declare (strict_types=1);

namespace app\admin\model\student;

use app\admin\model\Setting as SettingModel;
use app\common\model\student\Sign as SignModel;
use app\common\model\job\Job;
use think\db\exception\DbException;
use think\Paginator;

/**
 * 学员报名记录表模型
 * Class Sign
 * @package app\admin\model\student
 */
class Sign extends SignModel
{
    /**
     * 获取列表
     * @param array $param
     * @return Paginator
     * @throws DbException
     */
    public function getList($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);

        $order = [
            'a.student_sign_id' => 'desc',
        ];

        if (!empty($param['create_time']) && is_array($param['create_time'])) {
            $times = between_time2($param['create_time']);
            $filter[] = ['a.create_time', '>=', $times['start_time']];
            $filter[] = ['a.create_time', '<', $times['end_time']];
        } else if (!empty($param['create_time'])) {
            $order['a.create_time'] = $param['create_time'];
        }
        if (!empty($param['report_time']) && is_array($param['report_time'])) {
            $times = between_time2($param['report_time']);
            $filter[] = ['a.report_time', '>=', $times['start_time']];
            $filter[] = ['a.report_time', '<', $times['end_time']];
        } else if (!empty($param['report_time'])) {
            $order['a.report_time'] = $param['report_time'];
        }

        if (!empty($param['registration_time']) && is_array($param['registration_time'])) {
            $times = between_time($param['registration_time']);
            $filter[] = ['a.registration_time', '>=', $times['start_time']];
            $filter[] = ['a.registration_time', '<', $times['end_time'] + 86400];
        }

        // 查询列表记录
        $list = $query->alias('a')
            ->with(['job', 'store_user', 'avatar_file'])
//            ->field('a.*,b.full_name,b.id_card,b.avatar_file_id')
            ->field('a.student_sign_id,a.student_user_id,a.job_id,a.store_user_id,a.job_level,a.channel_name,a.status,a.report,a.report_time,a.registration_time,a.create_time,a.cert_no,a.cert_create_time,b.full_name,b.id_card,b.avatar_file_id,b.gender')
            ->join('student_user b', 'a.student_user_id=b.student_user_id')
            ->where($filter)
            ->where([
                'a.is_delete' => 0,
                'b.is_delete' => 0,
                'a.report' => 1,
            ])
            ->order($order)
            ->paginate($param['pageSize'] ?? 10);

        $config = SettingModel::getItem('web_basic');

        foreach ($list->items() as $item) {
            $item->certification_info = !empty($config['certification_info']) ? $config['certification_info'] : '';

            $item->answer_sheet_score = (new AnswerSheet())->where(['student_sign_id' => $item->student_sign_id])
                    ->order('answer_sheet_id', 'desc')
                    ->limit(1)
                    ->value('score') . '分';
            $item->qrcode_url = 'https://www.guopeicp.com/query.html?cert_id=' . $item->student_sign_id;
            $item->gender = $item->gender ? $item->gender : getGenderFromIdCard($item->id_card);
            $item->job_name = $item->job ? $item->job->job_name : '';
            $item->cert_create_time_text = $item->cert_create_time ? date("Y年m月d日", strtotime($item->cert_create_time)) : '';
            $item->cert_create_time_year = $item->cert_create_time ? date("Y", strtotime($item->cert_create_time)) : '';
            $item->cert_create_time_moon = $item->cert_create_time ? date("m", strtotime($item->cert_create_time)) : '';
            $item->cert_create_time_sun = $item->cert_create_time ? date("d", strtotime($item->cert_create_time)) : '';
        }
        return $list;
    }

    /**
     * 获取所有列表
     * @param array $param
     * @return Paginator
     * @throws DbException
     */
    public function getAllList($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);
        // 查询列表记录
        $list = $query
            ->with(['admin_user'])
            ->where($filter)
            ->where('is_delete', '=', '0')
            ->order(['sort' => 'desc', 'create_time' => 'desc'])
            ->select();
        return $list;
    }

    public function getQueryFilter($param)
    {
        $params = $this->setQueryDefaultValue($param, [
            'full_name' => '',
            'id_card' => '',
            'job_name' => '',
            'job_level' => '',
            'channel_name' => '',
            'status' => -1,
            'store_user_id' => 0,
        ]);

        $filter = [];
        !empty($params['full_name']) && $filter[] = ["full_name", "like", "%{$params['full_name']}%"];
        !empty($params['channel_name']) && $filter[] = ["channel_name", "like", "%{$params['channel_name']}%"];
        !empty($params['id_card']) && $filter[] = ["id_card", "like", "%{$params['id_card']}%"];
        if (!empty($params['job_name'])) {
            $job = (new Job())->where([
                'job_name' => $params['job_name'],
                'is_delete' => 0
            ])->find();
            $filter[] = ['job_id', '=', $job->job_id ?? ''];
        }
        !empty($params['job_level']) && $filter[] = ["job_level", "=", $params['job_level']];
        $params['status'] > -1 && $filter[] = ['status', '=', $params['status']];
        $params['store_user_id'] && $filter[] = ['store_user_id', 'in', $params['store_user_id']];
        return $filter;
    }

    /**
     * 增加记录
     * @param array $data
     * @return bool
     */
    public function add($data, $admin)
    {
        $data['admin_user_id'] = $admin['user']['admin_user_id'];
        return $this->save($data);
    }

    public function generateCertificate($data)
    {
        foreach ($data['ids'] as $item) {
            $cert_no = 'ZGGP' . date('Y') . rand(100000, 999999);
            $this->where('student_sign_id', '=', $item)->save([
                'status' => 3,
                'cert_no' => $cert_no,
                'cert_create_time' => time()
            ]);
        }
        return true;
    }

    public function printCert($data)
    {
        return $this->where('student_sign_id', 'in', $data['ids'])->save([
            'status' => 4,
        ]);
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     */
    public function edit(array $data)
    {
        return $this->save($data);
    }


    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }

    /**
     * 批量软删除
     * @return false|int
     */
    public function batchSetDelete($ids)
    {
        return $this->where($this->getPk(), 'in', $ids)->save(['is_delete' => 1]);
    }
}
